package com.ruoyi.project.channel.goodsInfo.controller;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Random;

import com.github.pagehelper.PageHelper;
import com.ruoyi.common.utils.security.ShiroUtils;
import com.ruoyi.project.channel.businessCashChange.service.IBusinessCashChangeService;
import com.ruoyi.project.channel.businessInfo.domain.BusinessInfo;
import com.ruoyi.project.channel.businessInfo.service.IBusinessInfoService;
import com.ruoyi.project.channel.businessInfoOrder.domain.BusinessInfoOrder;
import com.ruoyi.project.channel.businessInfoOrder.service.IBusinessInfoOrderService;
import com.ruoyi.project.channel.businessPauseOrderSetting.domain.BusinessPauseOrderSetting;
import com.ruoyi.project.channel.businessPauseOrderSetting.service.IBusinessPauseOrderSettingService;
import com.ruoyi.project.channel.incomeInfo.domain.IncomeInfo;
import com.ruoyi.project.channel.incomeInfo.service.IIncomeInfoService;
import com.ruoyi.project.channel.salesmanScore.service.SalesmanScoreServiceImpl;
import com.ruoyi.project.channel.userGoodsInfo.domain.UserGoodsInfo;
import com.ruoyi.project.channel.userGoodsInfo.service.IUserGoodsInfoService;
import com.ruoyi.project.channel.userLevelConfig.domain.UserLevelConfig;
import com.ruoyi.project.channel.vwBusinessCashStat.domain.VwBusinessCashStat;
import com.ruoyi.project.system.config.domain.Config;
import com.ruoyi.project.system.config.service.IConfigService;
import com.ruoyi.project.system.user.domain.User;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.project.channel.goodsInfo.domain.GoodsInfo;
import com.ruoyi.project.channel.goodsInfo.service.IGoodsInfoService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;

/**
 * 商品信息操作处理
 *
 * @author CAIN
 * @date 2021-01-17
 */
@Controller
@RequestMapping("/channel/goodsInfo")
public class GoodsInfoController extends BaseController {
    private String prefix = "channel/goodsInfo";

    @Autowired
    private IGoodsInfoService goodsInfoService;
    @Autowired
    private IBusinessInfoService businessInfoService;
    @Autowired
    private IIncomeInfoService incomeInfoService;
    @Autowired
    private IConfigService configService;
    @Autowired
    private IBusinessCashChangeService businessCashChangeService;
    @Autowired
    private IUserGoodsInfoService userGoodsInfoService;
    @Autowired
    private IBusinessInfoOrderService businessInfoOrderService;
    @Autowired
    private IBusinessPauseOrderSettingService businessPauseOrderSettingService;
    private static final Logger log = LoggerFactory.getLogger(GoodsInfoController.class);

    @RequiresPermissions("channel:goodsInfo:view")
    @GetMapping()
    public String goodsInfo() {
        return prefix + "/goodsInfo";
    }

    /**
     * 查询商品列表
     */
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(GoodsInfo goodsInfo) {
        startPage();
        List<GoodsInfo> list = goodsInfoService.selectGoodsInfoList(goodsInfo);
        return getDataTable(list);
    }

    /**
     * 导出商品列表
     */
    @RequiresPermissions("channel:goodsInfo:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(GoodsInfo goodsInfo) {
        List<GoodsInfo> list = goodsInfoService.selectGoodsInfoList(goodsInfo);
        ExcelUtil<GoodsInfo> util = new ExcelUtil<GoodsInfo>(GoodsInfo.class);
        return util.exportExcel(list, "goodsInfo");
    }

    /**
     * 新增商品
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存商品
     */
    @RequiresPermissions("channel:goodsInfo:add")
    @Log(title = "商品", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(GoodsInfo goodsInfo) {
        return toAjax(goodsInfoService.insertGoodsInfo(goodsInfo));
    }

    /**
     * 修改商品
     */
    @GetMapping("/edit/{productId}")
    public String edit(@PathVariable("productId") Long productId, ModelMap mmap) {
        GoodsInfo goodsInfo = goodsInfoService.selectGoodsInfoById(productId);
        mmap.put("goodsInfo", goodsInfo);
        return prefix + "/edit";
    }

    /**
     * 修改保存商品
     */
    @RequiresPermissions("channel:goodsInfo:edit")
    @Log(title = "商品", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(GoodsInfo goodsInfo) {
        return toAjax(goodsInfoService.updateGoodsInfo(goodsInfo));
    }

    /**
     * 删除商品
     */
    @RequiresPermissions("channel:goodsInfo:remove")
    @Log(title = "商品", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(goodsInfoService.deleteGoodsInfoByIds(ids));
    }

    /**
     * 用户状态修改
     */
    @Log(title = "商品管理", businessType = BusinessType.UPDATE)
    @PostMapping("/changeStatus")
    @RequiresPermissions("channel:goodsInfo:edit")
    @ResponseBody
    public AjaxResult changeStatus(GoodsInfo userLevelConfig) {
        return toAjax(goodsInfoService.updateGoodsInfo(userLevelConfig));
    }

    /**
     * 用户状态修改
     */
    @Log(title = "刷任务", businessType = BusinessType.UPDATE)
    @PostMapping("/doTask")
    @ResponseBody
    public AjaxResult doTask() {
        User user = ShiroUtils.getSysUser();
        long time = System.currentTimeMillis();
        VwBusinessCashStat vwBusinessCashStat = businessInfoService.getMyClickUserAmountInfo();
        log.info("获取getMyClickUserAmountInfo时长：" + (System.currentTimeMillis() - time));
        if (vwBusinessCashStat.isCanDoTask() == false) {
            return AjaxResult.error("task over");
        }
//        Date date = new Date();
//        List<Config> configs = configService.selectConfigList(new Config());
//        BigDecimal firstLevelRrate = BigDecimal.ZERO;
//        BigDecimal secondLevelRrate = BigDecimal.ZERO;
//        BigDecimal thirdLevelRrate = BigDecimal.ZERO;
//        for (int i = 0; i < configs.size(); i++) {
//            if (configs.get(i).getConfigKey().equals("first_level_rate")) {
//                String value = configs.get(i).getConfigValue();
//                firstLevelRrate = BigDecimal.valueOf(Double.valueOf(value));
//            } else if (configs.get(i).getConfigKey().equals("second_level_rate")) {
//                String value = configs.get(i).getConfigValue();
//                secondLevelRrate = BigDecimal.valueOf(Double.valueOf(value));
//            } else if (configs.get(i).getConfigKey().equals("third_level_rate")) {
//                String value = configs.get(i).getConfigValue();
//                thirdLevelRrate = BigDecimal.valueOf(Double.valueOf(value));
//            }
//        }
        // 获取当前可抢单金额 然后从商品表获取商品信息
        UserLevelConfig config = vwBusinessCashStat.getUserLevelConfig();
        log.info("getUserLevelConfig：时长：" + (System.currentTimeMillis() - time));
//		BigDecimal upperCommission = vwBusinessCashStat.getClickFrzzingCash().multiply(config.getCommissionPercentDay());
//		BigDecimal perCommison = upperCommission.divide(BigDecimal.valueOf(Long.valueOf(vwBusinessCashStat.getUserLevelConfig().getTaskNum()+"")), 4, RoundingMode.HALF_UP);
        // 今日还可以赚取的佣金  改为 用户总金额
//		BigDecimal remainCommission = upperCommission.subtract(vwBusinessCashStat.getTodayTaskCommission());
        // 今日剩余佣金 除以 每单佣金费率  得到最大商品价格 ，不能超过这个价格否则就超过了最大佣金数
        // 今日还剩佣金数除以今日还剩抢单数 平均每单还能抢多少金额
//		BigDecimal todayAvg = remainCommission.divide(BigDecimal.valueOf(Long.valueOf(vwBusinessCashStat.getTodayRemainTaskNum())), 4, RoundingMode.HALF_UP);
//		BigDecimal maxGoodPrice = todayAvg.divide(config.getCommissionPercent(), 4, RoundingMode.HALF_UP);

        // 设置商品价格以及佣金
        // 今日当前已抢单数
        BusinessInfoOrder businessInfoOrder = businessInfoOrderService.selectBusinessInfoOrderById(user.getUserId());
        log.info("selectBusinessInfoOrderById：时长：" + (System.currentTimeMillis() - time));
        // 获取是否被卡单了
        BusinessPauseOrderSetting searchS = new BusinessPauseOrderSetting();
        searchS.setUserId(user.getUserId());
        searchS.setPayStatus("未完成");
        List<BusinessPauseOrderSetting> settings = businessPauseOrderSettingService.selectBusinessPauseOrderSettingList(searchS);
        BusinessPauseOrderSetting curSetting = null;
        for (int j = 0; j < settings.size(); j++) {
            BusinessPauseOrderSetting setting = settings.get(j);
            if (Objects.equals(setting.getOrderNum(), businessInfoOrder.getDaySum() + 1)) {
                curSetting = setting;
                break;
            }
        }
        log.info("selectBusinessPauseOrderSettingList：时长：" + (System.currentTimeMillis() - time));
        // 商品信息
        UserGoodsInfo userGoodsInfo = new UserGoodsInfo();
        Random random = new Random();
        double randomValue = random.nextDouble(); // 生成 0 到 1 之间的随机数
        BigDecimal formattedValue = BigDecimal.valueOf(randomValue).setScale(2, BigDecimal.ROUND_HALF_UP);
        if (curSetting != null) {
            // 被卡单了 当前可用金额加上卡单金额
            userGoodsInfo.setGoodPrice(vwBusinessCashStat.getAmountSum().add(curSetting.getOrderPrice()).add(formattedValue));
            userGoodsInfo.setTaskPrice(curSetting.getOrderPrice()); // 卡单金额
            userGoodsInfo.setSettingId(curSetting.getSettingId());
            userGoodsInfo.setProfit(userGoodsInfo.getGoodPrice().multiply(config.getGrabbingPercent()).multiply(BigDecimal.valueOf(curSetting.getOrderTimes()))); // 卡单利润
        } else {
            // 普通利润
            Random random2 = new Random();
            double randomValue2 = 0.8 + (1.0 - 0.8) * random2.nextDouble(); // 生成 0.8 到 1 之间的随机数
            BigDecimal formattedValue2 = BigDecimal.valueOf(randomValue2).setScale(2, BigDecimal.ROUND_HALF_UP);
            userGoodsInfo.setGoodPrice(vwBusinessCashStat.getAmountSum().multiply(formattedValue2)); // 抢单的物品金额设置为用户客户金额的80%以上
            userGoodsInfo.setTaskPrice(BigDecimal.ZERO); // 无卡单金额
            userGoodsInfo.setProfit(userGoodsInfo.getGoodPrice().multiply(config.getGrabbingPercent())); // 利润
        }

        GoodsInfo search = new GoodsInfo();
        // 搜索未被使用的商品列表
        search.getParams().put("noContainUsedGoods", vwBusinessCashStat.getAmountSum());
//		search.getParams().put("price",maxGoodPrice.multiply(BigDecimal.valueOf(Double.valueOf("2"))));
//        if (businessInfo.getOrderPrice() != null && businessInfo.getOrderPrice().compareTo(BigDecimal.ZERO) != 0) {
//            // 被卡单则需要查找比当前价格高的商品
//            search.getParams().put("minAmount", businessInfo.getOrderPrice());
//            search.getParams().put("orderByAsc", "asc");
//        } else {
        search.getParams().put("maxAmount", userGoodsInfo.getGoodPrice());
        search.getParams().put("batch", businessInfoOrder.getBatch());
        search.getParams().put("userId", businessInfoOrder.getUserId());
        search.getParams().put("orderBy", "desc");
//        }
        PageHelper.startPage(1, 1, "");
        List<GoodsInfo> goodsInfos = goodsInfoService.selectGoodsInfoList(search);
        log.info("selectGoodsInfoList：时长：" + (System.currentTimeMillis() - time));
        if (goodsInfos.isEmpty()) {
            // 当前金额无法匹配到商品，请联系客服或者增加可做任务金额。
            goodsInfos = goodsInfoService.selectGoodsInfoList(new GoodsInfo());
            if (goodsInfos.isEmpty()) {
                return AjaxResult.error("can not match product");
            }
        }
        int i = new Random().nextInt(goodsInfos.size());
        GoodsInfo goodsInfo = goodsInfos.get(i);


        userGoodsInfo.setProductId(goodsInfo.getProductId());
        userGoodsInfo.setProductName(goodsInfo.getProductName());
        userGoodsInfo.setUserId(user.getUserId());
        Date d = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        String time1 = format.format(d);
        userGoodsInfo.setRemark(time1);
        userGoodsInfo.setImgUrl(goodsInfo.getImgUrl());
        userGoodsInfo.setCreateTime(new Date());
        userGoodsInfo.setPayStatus("NO_COMMIT");
        userGoodsInfo.setBatch(businessInfoOrder.getBatch());
        userGoodsInfoService.insertUserGoodsInfo(userGoodsInfo);
        log.info("insertUserGoodsInfo：时长：" + (System.currentTimeMillis() - time));
//		IncomeInfo incomeInfo = new IncomeInfo();
//		incomeInfo.setAmount(goodsInfo.getPrice());
//		// 当前佣金为 商品金额*刷单佣金比率
//		BigDecimal incomAmount = goodsInfo.getPrice().multiply(vwBusinessCashStat.getUserLevelConfig().getGrabbingPercent());
//		incomeInfo.setIncomeAmount(incomAmount);
//		incomeInfo.setOrderId(goodsInfo.getProductId());
//		incomeInfo.setType("3");
//		incomeInfo.setUserId(user.getUserId());
//        businessCashChangeService.insertBusinessCashChange(incomeInfo.getIncomeAmount(),incomeInfo.getUserId(), "4", "任务收入");
//        incomeInfoService.insertIncomeInfo(incomeInfo);
//        // 查询当前
//		String testCashDay = configService.selectConfigByKey("test_cash_back"); // 在返佣金额达到这直接  不返佣给上级
//		BigDecimal testCashDay_ = BigDecimal.valueOf(Double.valueOf(testCashDay));
//		// 今日任务返佣金额  vwBusinessCashStat.getTodayTaskCommission()
//
//        // 查找上级代理
//		BusinessInfo fistParent = businessInfoService.selectBusinessInfoById(businessInfo.getParentUserId());
//		if(fistParent != null && vwBusinessCashStat.getTodayTaskCommission().compareTo(testCashDay_) == 1){
//			BigDecimal fistCommission = incomAmount.multiply(firstLevelRrate);
//			incomeInfo = new IncomeInfo();
//			incomeInfo.setAmount(goodsInfo.getPrice());
//			incomeInfo.setIncomeAmount(fistCommission);
//			incomeInfo.setOrderId(goodsInfo.getProductId());
//			incomeInfo.setType("4");
//			incomeInfo.setChildType("1");
//			incomeInfo.setChildUserId(businessInfo.getUserId());
//			incomeInfo.setUserId(fistParent.getUserId());
//			incomeInfo.setUpdateTime(date);
//            businessCashChangeService.insertBusinessCashChange(incomeInfo.getIncomeAmount(),incomeInfo.getUserId(), "6", "一级代理收入");
//            incomeInfoService.insertIncomeInfo(incomeInfo);
//            // 二级代理
////			BusinessInfo secondParent = businessInfoService.selectBusinessInfoById(fistParent.getParentUserId());
////			if(secondParent != null){
////				BigDecimal secondCommission = incomAmount.multiply(secondLevelRrate);
////				incomeInfo = new IncomeInfo();
////				incomeInfo.setAmount(goodsInfo.getPrice());
////				incomeInfo.setIncomeAmount(secondCommission);
////				incomeInfo.setOrderId(goodsInfo.getProductId());
////				incomeInfo.setType("4");
////				incomeInfo.setChildType("2");
////				incomeInfo.setChildUserId(businessInfo.getUserId());
////				incomeInfo.setUserId(secondParent.getUserId());
////				incomeInfo.setUpdateTime(date);
////                businessCashChangeService.insertBusinessCashChange(incomeInfo.getIncomeAmount(),incomeInfo.getUserId(), "6", "二级代理收入");
////                incomeInfoService.insertIncomeInfo(incomeInfo);
////				// 三级级代理
////				BusinessInfo thirdParent = businessInfoService.selectBusinessInfoById(secondParent.getParentUserId());
////				if(thirdParent != null){
////					BigDecimal thirdCommission = incomAmount.multiply(thirdLevelRrate);
////					incomeInfo = new IncomeInfo();
////					incomeInfo.setAmount(goodsInfo.getPrice());
////					incomeInfo.setIncomeAmount(thirdCommission);
////					incomeInfo.setOrderId(goodsInfo.getProductId());
////					incomeInfo.setType("4");
////					incomeInfo.setChildType("3");
////					incomeInfo.setChildUserId(businessInfo.getUserId());
////					incomeInfo.setUserId(thirdParent.getUserId());
////					incomeInfo.setUpdateTime(date);
////					businessCashChangeService.insertBusinessCashChange(incomeInfo.getIncomeAmount(),incomeInfo.getUserId(), "6", "三级代理收入");
////					incomeInfoService.insertIncomeInfo(incomeInfo);
////				}
////            }
//		}
        businessInfoOrder.setDaySum(businessInfoOrder.getDaySum() + 1);
        businessInfoOrderService.updateBusinessInfoOrder(businessInfoOrder);
        log.info("updateBusinessInfoOrder：时长：" + (System.currentTimeMillis() - time));
        return AjaxResult.success("success", goodsInfo);
    }

    /**
     * 用户状态修改
     */
    @Log(title = "提交任务", businessType = BusinessType.UPDATE)
    @PostMapping("/submitTask")
    @ResponseBody
    public AjaxResult submitTask(UserGoodsInfo info) {
        User user = ShiroUtils.getSysUser();
//        BusinessInfoOrder businessInfoOrder = businessInfoOrderService.selectBusinessInfoOrderById(user.getUserId());
//        businessInfoOrder.setDaySum(businessInfoOrder.getDaySum() + 1);

        BusinessInfo businessInfo = businessInfoService.selectBusinessInfoById(user.getUserId());
        VwBusinessCashStat vwBusinessCashStat = businessInfoService.getMyClickUserAmountInfo();
//        if (vwBusinessCashStat.isCanDoTask() == false) {
//            return AjaxResult.error("task over");
//        }
        Date date = new Date();
        List<Config> configs = configService.selectConfigList(new Config());
        BigDecimal firstLevelRrate = BigDecimal.ZERO;
//        BigDecimal secondLevelRrate = BigDecimal.ZERO;
//        BigDecimal thirdLevelRrate = BigDecimal.ZERO;
        for (int i = 0; i < configs.size(); i++) {
            if (configs.get(i).getConfigKey().equals("first_level_rate")) {
                String value = configs.get(i).getConfigValue();
                firstLevelRrate = BigDecimal.valueOf(Double.valueOf(value));
            }
//            else if (configs.get(i).getConfigKey().equals("second_level_rate")) {
//                String value = configs.get(i).getConfigValue();
//                secondLevelRrate = BigDecimal.valueOf(Double.valueOf(value));
//            } else if (configs.get(i).getConfigKey().equals("third_level_rate")) {
//                String value = configs.get(i).getConfigValue();
//                thirdLevelRrate = BigDecimal.valueOf(Double.valueOf(value));
//            }
        }
        UserGoodsInfo goodsInfo = userGoodsInfoService.selectUserGoodsInfoById(info.getOrderId());
        if (!goodsInfo.getPayStatus().equals("NO_COMMIT")) {
            return AjaxResult.error("HAS COMMIT");
        }
        if (vwBusinessCashStat.getAmountSum().compareTo(goodsInfo.getGoodPrice()) < 0) {
            // 总金额小于 商品金额则不允许提交
            return AjaxResult.error("NO ENOUGH MONEY");
        }

        if (goodsInfo.getSettingId() != null) {
            BusinessPauseOrderSetting setting = businessPauseOrderSettingService.selectBusinessPauseOrderSettingById(goodsInfo.getSettingId());
            if (setting != null) {
                setting.setUpdateTime(new Date());
                setting.setPayStatus("已完成");
                businessPauseOrderSettingService.updateBusinessPauseOrderSetting(setting);
            }
        }
//        businessInfoOrderService.updateBusinessInfoOrder(businessInfoOrder);
        goodsInfo.setPayStatus("SUBMIT");
        goodsInfo.setUpdateTime(new Date());
        userGoodsInfoService.updateUserGoodsInfo(goodsInfo);

        IncomeInfo incomeInfo = new IncomeInfo();
        incomeInfo.setAmount(goodsInfo.getGoodPrice());
        // 当前佣金为 商品金额*刷单佣金比率
        BigDecimal incomAmount = goodsInfo.getProfit();
        incomeInfo.setIncomeAmount(incomAmount);
        incomeInfo.setOrderId(goodsInfo.getProductId());
        incomeInfo.setType("3");
        incomeInfo.setUserId(user.getUserId());
        businessCashChangeService.insertBusinessCashChange(incomeInfo.getIncomeAmount(), incomeInfo.getUserId(), "4", "任务收入");
        incomeInfoService.insertIncomeInfo(incomeInfo);
        // 查询当前
//        String testCashDay = configService.selectConfigByKey("test_cash_back"); // 在返佣金额达到这直接  不返佣给上级
//        BigDecimal testCashDay_ = BigDecimal.valueOf(Double.valueOf(testCashDay));
        // 今日任务返佣金额  vwBusinessCashStat.getTodayTaskCommission()
        // 查找上级代理
        BusinessInfo fistParent = businessInfoService.selectBusinessInfoById(businessInfo.getParentUserId());
//        if (fistParent != null && vwBusinessCashStat.getTodayTaskCommission().compareTo(testCashDay_) > 0) {
        if (fistParent != null) {
            BigDecimal fistCommission = incomAmount.multiply(firstLevelRrate);
            incomeInfo = new IncomeInfo();
            incomeInfo.setAmount(goodsInfo.getGoodPrice());
            incomeInfo.setIncomeAmount(fistCommission);
            incomeInfo.setOrderId(goodsInfo.getProductId());
            incomeInfo.setType("4");
            incomeInfo.setChildType("1");
            incomeInfo.setChildUserId(businessInfo.getUserId());
            incomeInfo.setUserId(fistParent.getUserId());
            incomeInfo.setUpdateTime(date);
            businessCashChangeService.insertBusinessCashChange(incomeInfo.getIncomeAmount(), incomeInfo.getUserId(), "6", "一级代理收入");
            incomeInfoService.insertIncomeInfo(incomeInfo);
            // 二级代理
//			BusinessInfo secondParent = businessInfoService.selectBusinessInfoById(fistParent.getParentUserId());
//			if(secondParent != null){
//				BigDecimal secondCommission = incomAmount.multiply(secondLevelRrate);
//				incomeInfo = new IncomeInfo();
//				incomeInfo.setAmount(goodsInfo.getPrice());
//				incomeInfo.setIncomeAmount(secondCommission);
//				incomeInfo.setOrderId(goodsInfo.getProductId());
//				incomeInfo.setType("4");
//				incomeInfo.setChildType("2");
//				incomeInfo.setChildUserId(businessInfo.getUserId());
//				incomeInfo.setUserId(secondParent.getUserId());
//				incomeInfo.setUpdateTime(date);
//                businessCashChangeService.insertBusinessCashChange(incomeInfo.getIncomeAmount(),incomeInfo.getUserId(), "6", "二级代理收入");
//                incomeInfoService.insertIncomeInfo(incomeInfo);
//				// 三级级代理
//				BusinessInfo thirdParent = businessInfoService.selectBusinessInfoById(secondParent.getParentUserId());
//				if(thirdParent != null){
//					BigDecimal thirdCommission = incomAmount.multiply(thirdLevelRrate);
//					incomeInfo = new IncomeInfo();
//					incomeInfo.setAmount(goodsInfo.getPrice());
//					incomeInfo.setIncomeAmount(thirdCommission);
//					incomeInfo.setOrderId(goodsInfo.getProductId());
//					incomeInfo.setType("4");
//					incomeInfo.setChildType("3");
//					incomeInfo.setChildUserId(businessInfo.getUserId());
//					incomeInfo.setUserId(thirdParent.getUserId());
//					incomeInfo.setUpdateTime(date);
//					businessCashChangeService.insertBusinessCashChange(incomeInfo.getIncomeAmount(),incomeInfo.getUserId(), "6", "三级代理收入");
//					incomeInfoService.insertIncomeInfo(incomeInfo);
//				}
//            }
        }
        return AjaxResult.success("success", goodsInfo);
    }


    /**
     * 用户状态修改
     */
    @Log(title = "抢单", businessType = BusinessType.UPDATE)
    @PostMapping("/grabbing")
    @ResponseBody
    public AjaxResult grabbing() {

        // 获取抢单池数据 判断是否还能抢单
//        int hour = new Date().getHours();
//        if (Grabbing.concurrentHashMap.get(hour + "") == null) {
//            // 当前时间是否已经开始抢单
//            return AjaxResult.error("no time");
//        }
//        int i = new Random().nextInt(5);
//        if (i != 1 && i != 3) {
//            return AjaxResult.error("no lottery");
//        }
//        User user = ShiroUtils.getSysUser();
//        VwBusinessCashStat vwBusinessCashStat = businessInfoService.getMyClickUserAmountInfo();
//        if (vwBusinessCashStat.isCanDoTask()) {
//            // 提示先做任务 做完任务再来抢单
//            return AjaxResult.error("need task first");
//        }
//
//        if (vwBusinessCashStat.getTodayRemainClickNum() <= 0) {
//            return AjaxResult.error("grabbing over");
//        }
//        String sumStr = (String) Grabbing.concurrentHashMap.get(hour + "");
//        int sum = Integer.parseInt(sumStr); // 当前还剩的单数
//        if (sum == 0) {
//            return AjaxResult.error("grabbing over");
//        }
//        sum = sum - 1;
//        Grabbing.concurrentHashMap.put(hour + "", sum + "");
//        Date date = new Date();
//        // 获取当前可抢单金额 然后从商品表获取商品信息
//        UserLevelConfig config = vwBusinessCashStat.getUserLevelConfig();
//        // 今日剩余佣金 除以 每单佣金费率  得到最大商品价格 ，不能超过这个价格否则就超过了最大佣金数
//        String value = configService.selectConfigByKey("grabbing_amount");
//
//
//        GoodsInfo search = new GoodsInfo();
//        String[] values = value.split("-");
//        if (values.length == 2) {
//            search.getParams().put("minAmount", values[0].trim());
//            search.getParams().put("maxAmount", values[1].trim());
//        } else {
//            search.getParams().put("minAmount", 0);
//            search.getParams().put("maxAmount", 1000);
//        }
//        List<GoodsInfo> goodsInfos = goodsInfoService.selectGoodsInfoList(search);
//        GoodsInfo goodsInfo = goodsInfos.get(new Random().nextInt(goodsInfos.size()));
//        IncomeInfo incomeInfo = new IncomeInfo();
//        incomeInfo.setAmount(goodsInfo.getPrice());
//        incomeInfo.setIncomeAmount(goodsInfo.getPrice().multiply(config.getGrabbingPercent()));
//        incomeInfo.setOrderId(goodsInfo.getProductId());
////		incomeInfo.setUpdateTime(date);
//        incomeInfo.setType("1"); // 自己抢单
//        incomeInfo.setUserId(user.getUserId());
//        businessCashChangeService.insertBusinessCashChange(incomeInfo.getIncomeAmount(), incomeInfo.getUserId(), "5", "抢单收入");
//        incomeInfoService.insertIncomeInfo(incomeInfo);
//        return AjaxResult.success("success", goodsInfo);
        return null;
    }
}
